<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}工序`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="工序编码" prop="processCode">
        <el-input v-model="drawerProps.row!.processCode" placeholder="请输入工序编码" clearable />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input v-model="drawerProps.row!.processName" placeholder="请输入工序名称" clearable />
      </el-form-item>
      <el-form-item label="工序参数" prop="parameters">
        <el-input
          v-model="parametersText"
          type="textarea"
          :rows="4"
          placeholder="请输入工序参数，格式：key1=value1,key2=value2"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProcessForm">
import { ref, reactive, computed } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Process, createProcess } from "@/api/modules/process";

const rules = reactive({
  processCode: [{ required: true, message: "请输入工序编码", trigger: "blur" }],
  processName: [{ required: true, message: "请输入工序名称", trigger: "blur" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Process.ProcessListItem>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 工序参数的文本表示
const parametersText = computed({
  get: () => {
    if (!drawerProps.value.row.parameters) return '';
    return Object.entries(drawerProps.value.row.parameters)
      .map(([key, value]) => `${key}=${value}`)
      .join(',');
  },
  set: (value: string) => {
    if (!value.trim()) {
      drawerProps.value.row.parameters = {};
      return;
    }
    
    const params: Record<string, string> = {};
    value.split(',').forEach(pair => {
      const [key, val] = pair.split('=');
      if (key && val) {
        params[key.trim()] = val.trim();
      }
    });
    drawerProps.value.row.parameters = params;
  }
});

// 接收父组件传过来的参数
const open = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      const params: Process.CreateProcessRequest = {
        processCode: drawerProps.value.row.processCode!,
        processName: drawerProps.value.row.processName,
        parameters: drawerProps.value.row.parameters
      };
      
      await createProcess(params);
      ElMessage.success({ message: `${drawerProps.value.title}工序成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.error(`${drawerProps.value.title}工序失败:`, error);
      ElMessage.error(`${drawerProps.value.title}工序失败`);
    }
  });
};

defineExpose({
  open
});
</script>